from django.http import JsonResponse
from django.shortcuts import render, HttpResponse
from .models import inject_data, filter_data, proxy_data, sqlmap_log
from .proxy import start_proxy, shutdown_proxy
from lib.config_json import *
from pentest.injection import *
import socket
from django.views.decorators.csrf import csrf_exempt
import subprocess
from django.contrib.auth.decorators import login_required
from .auth import *
import psutil
import os




def proxy(request):
    domain = request.GET.get("domain") or ""
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    result = sock.connect_ex(('127.0.0.1', PROXY_LISTEN_PORT))  # 监听端口的开启情况
    if result == 0:
        port_status = "启动"
    else:
        port_status = "关闭"
    host = PROXY_LISTEN_HOST
    port = PROXY_LISTEN_PORT
    return render(request, "pentest/proxy.html", locals())




def index(request):
    return render(request, "pentest/injection.html", locals())


def passive_sqli(request):
    domain = request.GET.get("domain") or ""
    status = request.GET.get("status") or ""
    num = int(os.popen("ps aux | grep sqlmapapi | grep -v grep | wc -l").readline().replace('\n', ''))
    t = int(os.popen("ps aux | grep sqlmap | grep -v sqlmapapi | grep -v grep | wc -l").readline().replace('\n', ''))

    if len(SQLMAP_API_SERVER) == num:
        run_status = "启动"
    else:
        run_status = "关闭"
    return render(request, "pentest/passive_sqli.html", locals())


@csrf_exempt
def start_sqlmap(request):
    if request.method == 'POST':
        tp = request.POST.get('type')
        domain = request.POST.get('domain') or ""
        # results = filter_data.objects.filter(host__icontains=domain)
        if tp == "start":
            results = filter_data.objects.filter(host__icontains=domain)
            for result in results:
                run_sqlmap.delay(result.id,"start")
        elif tp == "restart":
            results = inject_data.objects.all()
            for result in results:
                result.status = '0'
                result.taskid = ''
                result.dbms = ""
                result.parameter = ""
                result.log_status = ""
                result.run_status = ""
                result.save()
                run_sqlmap.delay(result.id,"restart")


        else:
            return JsonResponse({"code": 0, "msg": "类型错误，请选择正确的类型w(ﾟДﾟ)w"})

        return JsonResponse({"code": 200, "msg": "开始运行，三秒后自动关闭(๑•̀ㅂ•́)و✧"})

    return render(request, "pentest/sqlmap.html", locals())


def get_inject_data(request):
    domain = request.GET.get('domain') or ""
    status = request.GET.get("status") or ""
    try:
        page = int(request.GET.get("page")) or 1
    except:
        page = 1
    try:
        limit = int(request.GET.get("limit")) or 30
    except:
        limit = 30
    start = (page - 1) * limit
    end = page * limit
    if status == '1':
        results = inject_data.objects.filter(host__icontains=domain, run_status="running")[start:end].values("id",
                                                                                                             "taskid",
                                                                                                             "run_status",
                                                                                                             "parameter",
                                                                                                             "host",
                                                                                                             "log_status")
        count = inject_data.objects.all().count()
        r = inject_data.objects.filter(host__icontains=domain)
        if len(r) != 0:
            get_runstatus(r)

    elif status == '2':
        results = inject_data.objects.filter(host__icontains=domain, run_status="terminated")[start:end].values("id",
                                                                                                                "taskid",
                                                                                                                "run_status",
                                                                                                                "parameter",
                                                                                                                "host",
                                                                                                                "log_status")
        count = inject_data.objects.all().count()
        r = inject_data.objects.filter(host__icontains=domain)
        if len(r) != 0:
            get_runstatus(r)
    elif status == '3':
        results = inject_data.objects.filter(host__icontains=domain, status="2", run_status="terminated")[
                  start:end].values("id",
                                    "taskid",
                                    "run_status",
                                    "parameter",
                                    "host",
                                    "log_status")
        count = inject_data.objects.all().count()
        r = inject_data.objects.filter(host__icontains=domain)
        if len(r) != 0:
            get_runstatus(r)
    else:
        results = inject_data.objects.filter(host__icontains=domain)[start:end].values("id", "taskid", "run_status",
                                                                                       "parameter", "host",
                                                                                       "log_status")
        count = inject_data.objects.all().count()
        r = inject_data.objects.filter(host__icontains=domain)
        if len(r) != 0:
            get_runstatus(r)
    data = []
    for i in results:
        data.append(i)
    return JsonResponse({"code": 0, "msg": "", "count": count, "data": data}, safe=False)


def update_auth(request):
    if request.method == 'POST':
        tp = request.POST.get('type')
        parm = request.POST.get('parm')
        domain = request.POST.get('domain')
        modify_content = request.POST.get('content')
        modify_auth(tp=tp, parm=parm, host=domain, modify=modify_content)
        return JsonResponse({"code": 200, "msg": "更新验证成功o(*≧▽≦)ツ┏━┓"})

    return render(request, "pentest/update_auth.html", locals())


def check_log(request):
    taskid = request.GET.get("taskid")
    try:
        status = 0
        data = filter_data.objects.filter(taskid=taskid)[0].data_packet
        log = sqlmap_log.objects.get(taskid=taskid).log
    except:
        status = 1
        msg = "runing"

    return render(request, "pentest/check_log.html", locals())


def check_nlog(request):
    taskid = request.GET.get("taskid")
    # try:
    status = 0
    url = inject_data.objects.get(taskid=taskid).api_address + '/scan/' + taskid + '/log'
    r = requests.get(url=url, headers={'Content-Type': 'application/json'})
    logs = r.json()['log']
    log = ""
    for i in logs:
        log = log + "[" + i['level'] + "]" + "[" + i['time'] + "]" + i['message'] + "\n"

    return render(request, "pentest/check_nlog.html", locals())


def check_data(request):
    taskid = request.GET.get("taskid")
    data = filter_data.objects.filter(taskid=taskid)[0].data_packet

    return render(request, "pentest/check_data.html", locals())

#连接API应该有两种，一种是本地启动API，一种是远程连接
def start_sqlmap_api(request):
    #本地多种网卡的IP
    ips = []
    addrs = socket.getaddrinfo(socket.gethostname(), None)
    for item in addrs:
        if "." in item[4][0]:
            ips.append(item[4][0])
    ips.append("127.0.0.1")
    for server in SQLMAP_API_SERVER:
        host = server.replace("http://", "").split(':')[0]
        port = server.replace("http://", "").split(':')[1]
        if host in ips:
            cmdline = "sqlmapapi -s  -H " + host + " -p " + port + " >/tmp/sqlmap_log 2>&1 &"
            os.system(cmdline)

    return JsonResponse({"code": 200, "msg": "开始成功φ(≧ω≦*)♪"})


#如果远程你也停止不了，这里就不管，直接停本地把
def stop_sqlmap_api(request):
    for server in SQLMAP_API_SERVER:
        host = server.replace("http://", "").split(':')[0]
        port = server.replace("http://", "").split(':')[1]
        os.system("ps aux | grep sqlmapapi -s | awk {'print$2'} | xargs kill -9 ")
    return JsonResponse({"code": 200, "msg": "停止成功(* ￣3)(ε￣ *)"})


def filter_packect(request):
    filter()
    return JsonResponse({"code": 200, "msg": "过滤成功（づ￣3￣）づ╭❤～"})


def starting_proxy(request):
    start_proxy()
    return JsonResponse({"code": 0, "msg": "error!!!!"})


def display_proxy_data(request):
    domain = request.GET.get('domain') or ""
    t = request.GET.get("type")
    try:
        page = int(request.GET.get("page")) or 1
    except:
        page = 1
    try:
        limit = int(request.GET.get("limit")) or 30
    except:
        limit = 30
    start = (page - 1) * limit
    end = page * limit
    if t == "all":
        results = proxy_data.objects.filter(host__icontains=domain)[start:end].values("id", "method", "url",
                                                                                      "request_content")
        count = proxy_data.objects.all().count()
    elif t == "filter":

        results = filter_data.objects.filter(host__icontains=domain)[start:end].values("id", "url", "parm", )
        count = filter_data.objects.all().count()

    data = []
    for i in results:
        data.append(i)
    return JsonResponse({"code": 0, "msg": "", "count": count, "data": data}, safe=False)


def check_filter_data(request):
    id = request.GET.get("id")
    result = filter_data.objects.get(id=id)
    data = result.data_packet

    return render(request, "pentest/check_filter_data.html", locals())



def resart_injection_api(request):
    taskid = request.GET.get("taskid")
    result = inject_data.objects.get(taskid=taskid)
    run_sqlmap.delay(result.id, "restart")

    return JsonResponse({"msg":"注入ing"})
